package com.epam.tcs.actions.pages;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epam.tcs.actions.BreadCrumb;
import com.epam.tcs.dao.factory.DAO;
import com.epam.tcs.dao.hibernate.entities.Program;

public class ProgramPage extends PageAbstract {

	@Override
	public void doExec(HttpServletRequest req, HttpServletResponse res) {
		String target = req.getRequestURI().substring(
				req.getContextPath().length());

		String[] tarr = target.split("/");

		BreadCrumb.add(req, res, "Программы", "/tcs/program");
		try {
			if ((tarr.length == 4) && tarr[3].equals("add")) {
				addProgram(req, res);
			} else if ((tarr.length == 4) && tarr[3].equals("del")) {
				delProgram(req, res);
			} else if ((tarr.length == 4) && tarr[3].equals("edit")) {
				editProgram(req, res);
			} else {
				listPrograms(req, res);
			}
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void listPrograms(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		DAO<Program> program = dao.getProgramDAO();
		req.setAttribute("widget", "program");
		req.getSession().setAttribute("listPrograms", program.getAllElements());
		outputPage("program/program.jsp", req, res);
	}

	private void editProgram(HttpServletRequest req, HttpServletResponse res) {
		// TODO Auto-generated method stub

	}

	private void delProgram(HttpServletRequest req, HttpServletResponse res) {
		// TODO Auto-generated method stub

	}

	private void addProgram(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		BreadCrumb.add(req, res, "Добавить программу", "/tcs/program/add");
		if (req.getMethod() == "POST" && this.validateProgramForm(req)) {
			DAO<Program> program = dao.getProgramDAO();
			Program p = new Program();
			p.setName(req.getParameter("caption"));
			p.setHours(Integer.parseInt(req.getParameter("hours")));
			p.setDescription(req.getParameter("description"));

			if (program.addElement(p) != 0L) {
				req.setAttribute("message", "Программа \"" + p.getName()
						+ "\" успешно добавлена.");
			}
		}
		req.setAttribute("widget", "add_program");
		outputPage("program/program_form.jsp", req, res);

	}

	private boolean validateProgramForm(HttpServletRequest req) {
		// TODO Auto-generated method stub
		return true;
	}

}
